package org.javaboy.account.service;

import io.seata.rm.tcc.api.BusinessActionContext;
import org.javaboy.account.mapper.AccountMapper;
import org.javaboy.account.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class AccountService {

    @Autowired
    AccountMapper accountMapper;

    @Transactional
    public boolean rollback(BusinessActionContext actionContext) {
        Integer userId = ((Integer) actionContext.getActionContext("userId"));
        Double money = ((BigDecimal) actionContext.getActionContext("money")).doubleValue();
        Account account = accountMapper.selectById(userId);
        if (account.getFreeze() >= money) {
            account.setFreeze(account.getFreeze() - money);
            account.setMoney(account.getMoney() + money);
            return accountMapper.update(account) == 1;
        }
        return true;
    }

    @Transactional
    public boolean commit(BusinessActionContext actionContext) {
        Integer userId = ((Integer) actionContext.getActionContext("userId"));
        Double money = ((BigDecimal) actionContext.getActionContext("money")).doubleValue();
        Account account = accountMapper.selectById(userId);
        if (account.getFreeze() < money) {
            return true;
        }
        account.setFreeze(account.getFreeze() - money);
        return accountMapper.update(account) == 1;
    }

    @Transactional
    public boolean deduce(Integer userId, Double money) {
        Account account = accountMapper.selectById(userId);
        if (account == null) {
            return false;
        }
        if (account.getMoney() < money) {
            return false;
        }
        account.setMoney(account.getMoney() - money);
        account.setFreeze(account.getFreeze() + money);
        return accountMapper.update(account) == 1;
    }
}
